<script setup lang="ts">
import { getCurrentInstance, ref } from "vue";
import { onLoad, onPullDownRefresh, onUnload } from "@dcloudio/uni-app";
import { useList, useTabs } from "@/hooks/page";
import {
  guider_file_list_api,
  guider_file_add_api,
  guider_file_del_api,
} from "@/package/my/api/guider_home";
import { upload_up, mini_upload_up } from "@/api/upload";
import { chooseMedia, uploadWrapper } from "@/utils/meida";
import { Toast } from "@/utils/toast";

import ResourceTabItem from "./components/resource-tab-item.vue";
import ListEmpty from "@/components/list/empty.vue";
import ListMore from "@/components/list/more.vue";
import FormButton from "@/components/form/button.vue";
import Swipe from "@/components/swipe/swipe.vue";
import PopupModal from "@/components/popup/modal.vue";

onLoad(() => {
  tabChange({ detail: { current: 0 } });

  eventChannel = (
    getCurrentInstance()?.proxy as any
  ).getOpenerEventChannel() as UniApp.EventChannel;
});
onPullDownRefresh(() => {
  reloadData()
    .then(() => uni.stopPullDownRefresh())
    .catch(() => uni.stopPullDownRefresh());
});
onUnload(() => {
  eventChannel?.emit("ev-resource-edit", tempData.isEdit ? "edit" : "");
});

const reloadData = () => {
  return tabData.index === 0 ? reloadList() : reloadList2();
};

const { listData, listStatus, listLoadMore, reloadList, loadMoreList } =
  useList({ page: 1, page_size: 10 }, (query) => {
    return guider_file_list_api({ ...query, type: 1 });
  });

const {
  listData: listData2,
  listStatus: listStatus2,
  listLoadMore: listLoadMore2,
  reloadList: reloadList2,
  loadMoreList: loadMoreList2,
} = useList({ page: 1, page_size: 20 }, (query) => {
  return guider_file_list_api({ ...query, type: 2 });
});

const tabList = ["视频", "照片"];
const { tabData, tabClick, tabChange } = useTabs((index) => {
  index === 0 ? reloadList() : reloadList2();
});

const previewVisible = ref(false);
const previewIndex = ref(0);
const previewList = ref<any[]>([]);
const previewClick = (index: number) => {
  if (tabData.index === 0) {
    const video = listData.value[index];
    previewIndex.value = 0;
    previewList.value = [
      {
        id: video.id,
        type: "video",
        url: video.file_url,
        poster: video.video_pic,
      },
    ];
  } else {
    previewIndex.value = index;
    previewList.value = listData2.value.map((i) => {
      return { id: i.id, type: "img", url: i.file_url };
    });
  }

  previewVisible.value = true;
};

const uploadClick = () => {
  if (tabData.index === 0) {
    chooseMedia({ count: 9, mediaType: ["video"] }, (fileList) => {
      Toast.showLoading();
      uploadWrapper(
        fileList.map((i) => i.tempFilePath),
        (resourceList) => {
          guider_file_add_api({
            type: 1,
            file_url: resourceList,
          })
            .then(() => {
              reloadData();
              Toast.hideLoading();
              tempData.isEdit = true;
            })
            .catch(() => Toast.hideLoading());
        },
        (path) => {
          return mini_upload_up(path, { type: 6 }).then((resp) => {
            return resp.map((i) => i.url);
          });
        }
      );
    });
  } else {
    chooseMedia({ count: 9, mediaType: ["image"] }, (fileList) => {
      Toast.showLoading();
      uploadWrapper(
        fileList.map((i) => i.tempFilePath),
        (resourceList) => {
          guider_file_add_api({
            type: 2,
            file_url: resourceList,
          })
            .then(() => {
              reloadData();
              Toast.hideLoading();
              tempData.isEdit = true;
            })
            .catch(() => Toast.hideLoading());
        },
        (path) => {
          return upload_up(path, { type: 7 }).then((resp) => {
            return resp.map((i) => i.url);
          });
        }
      );
    });
  }
};

const delClick = () => {
  popupModal.value?.show({ content: "是否确认删除？" }, () => {
    Toast.showLoading();
    guider_file_del_api({ id: previewList.value[previewIndex.value].id })
      .then(() => {
        reloadData();
        Toast.hideLoading();
        tempData.isEdit = true;
      })
      .catch(() => Toast.hideLoading());
  });
};

const popupModal = ref<InstanceType<typeof PopupModal>>();
let eventChannel: UniApp.EventChannel | undefined = undefined;
const tempData = { isEdit: false };
</script>

<template>
  <view class="resource-tab">
    <view
      class="resource-tab-item"
      v-for="(i, d) of tabList"
      :key="d"
      @click="tabClick(d)"
    >
      <ResourceTabItem :isActive="tabData.index === d" :text="i" />
    </view>
  </view>

  <swiper
    class="resource-swiper"
    :current="tabData.current"
    @change="tabChange"
  >
    <swiper-item>
      <scroll-view
        class="resource-video"
        scroll-y
        @scroll="listLoadMore = true"
        @scrolltolower="loadMoreList"
      >
        <ListEmpty v-if="listData.length === 0 && listStatus === 'noMore'" />
        <template v-else>
          <view class="resource-video-wrapper">
            <view
              class="resource-video-item"
              v-for="(i, d) of listData"
              :key="i.id"
              @click="previewClick(d)"
            >
              <image
                class="resource-video-img"
                :src="i.video_pic"
                mode="aspectFill"
              />
              <image
                class="resource-video-icon"
                src="@/package/my/static/guider-resource-video.png"
              />
            </view>
          </view>
          <ListMore
            v-if="listLoadMore"
            :status="listStatus"
            safeAreaInsetBottom
          />
        </template>
      </scroll-view>
    </swiper-item>

    <swiper-item>
      <scroll-view
        class="resource-photo"
        scroll-y
        @scroll="listLoadMore2 = true"
        @scrolltolower="loadMoreList2"
      >
        <ListEmpty v-if="listData2.length === 0 && listStatus2 === 'noMore'" />
        <template v-else>
          <view class="resource-photo-wrapper">
            <image
              class="resource-photo-item"
              v-for="(i, d) of listData2"
              :key="i.id"
              :src="i.file_url"
              mode="aspectFill"
              @click="previewClick(d)"
            />
          </view>
          <ListMore
            v-if="listLoadMore2"
            :status="listStatus2"
            safeAreaInsetBottom
          />
        </template>
      </scroll-view>
    </swiper-item>
  </swiper>

  <view class="resource-btn">
    <view @click="uploadClick">
      <FormButton>上传{{ tabData.index === 0 ? "视频" : "图片" }}</FormButton>
    </view>
  </view>

  <uni-transition
    :show="previewVisible"
    mode-class="fade"
    :styles="{ position: 'fixed', left: 0, top: 0 }"
  >
    <view class="resource-preview" @click="previewVisible = false">
      <Swipe
        v-model="previewIndex"
        :listData="previewList"
        mode="aspectFit"
        objectFit="contain"
      />
      <view class="resource-preview-index" v-if="previewList.length > 1">
        {{ previewIndex + 1 }}/{{ previewList.length }}
      </view>
      <image
        class="resource-preview-del"
        src="@/package/my/static/guider-resource-del.png"
        @click="delClick"
      />
    </view>
  </uni-transition>

  <PopupModal ref="popupModal" />
</template>

<style lang="scss">
page {
  padding-bottom: 0;
  background-color: #ffffff;
}

.resource-tab {
  display: flex;
  align-items: center;
  height: 88rpx;
  padding-left: 30rpx;

  .resource-tab-item {
    padding: 0 30rpx;
    margin-right: 40rpx;
  }
}

.resource-swiper {
  height: calc(100vh - 88rpx);
}

.resource-video {
  height: 100%;

  .resource-video-wrapper {
    padding-top: 20rpx;
  }

  .resource-video-item {
    position: relative;
    margin: 0 30rpx 20rpx;
  }

  .resource-video-img {
    display: block;
    width: 100%;
    height: 388rpx;
    border-radius: 20rpx;
  }

  .resource-video-icon {
    position: absolute;
    left: 50%;
    top: 50%;
    width: 80rpx;
    height: 80rpx;
    transform: translate(-50%, -50%);
  }
}

.resource-photo {
  height: 100%;

  .resource-photo-wrapper {
    display: flex;
    flex-wrap: wrap;
    padding-left: 30rpx;
    padding-top: 20rpx;
  }

  .resource-photo-item {
    width: 336rpx;
    height: 336rpx;
    margin-right: 18rpx;
    margin-bottom: 20rpx;
    border-radius: 20rpx;
  }
}

.resource-btn {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 106rpx;
  padding: 14rpx 60rpx env(safe-area-inset-bottom);
  background-color: #ffffff;
}

.resource-preview {
  position: relative;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.9);

  .resource-preview-index {
    position: absolute;
    left: 50%;
    top: 10rpx;
    font-size: 36rpx;
    color: #ffffff;
    line-height: 50rpx;
    transform: translateX(-50%);
  }

  .resource-preview-del {
    position: absolute;
    top: 78rpx;
    right: 30rpx;
    width: 36rpx;
    height: 42rpx;
  }
}
</style>